package com.zhang.servicemap.remote;

import com.zhang.internalcommon.constant.AmapConfigConstant;
import com.zhang.internalcommon.response.DirectionResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class MapDirectionClient {
	@Value("${amap.key}")
	private String myKey;

	@Autowired
	private RestTemplate restTemplate;

	public DirectionResponse direction(String depLongitude, String depLatitude, String destLongitude, String destLatitude) {
		// 	组装调用url
		// 	https://restapi.amap.com/v3/direction/driving?origin=116.481028,39.989643&destination=116.465302,40.004717&extensions=all&output=xml&key=<用户的key>
		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append(AmapConfigConstant.DIRECTION_URL);
		urlBuilder.append("?");
		urlBuilder.append("origin=" + depLongitude + "," + depLatitude);
		urlBuilder.append("&destination=" + destLongitude + "," + destLatitude);
		urlBuilder.append("&extensions=all&output=json&key=");
		urlBuilder.append(myKey);
		// log.info(urlBuilder.toString());

		// 	调用高德API
		ResponseEntity<String> directionEntity = restTemplate.getForEntity(urlBuilder.toString(), String.class);
		log.info("direction response: {}", directionEntity.getBody());
		// 	解析接口
		DirectionResponse directionResponse = parseDirectionResponse(directionEntity.getBody());
		return directionResponse;
	}

	private DirectionResponse parseDirectionResponse(String directionString) {
		DirectionResponse directionResponse = null;
		try {
			JSONObject result = JSONObject.fromObject(directionString);
			if (result.has(AmapConfigConstant.STATUS)) {
				int status = result.getInt(AmapConfigConstant.STATUS);
				if (status == 1) {
					if (result.has(AmapConfigConstant.ROUTE)) {
						JSONObject routeObject = result.getJSONObject(AmapConfigConstant.ROUTE);
						JSONArray pathsArray = routeObject.getJSONArray(AmapConfigConstant.PATHS);
						JSONObject pathObject = pathsArray.getJSONObject(0);
						directionResponse = new DirectionResponse();
						if (pathObject.has(AmapConfigConstant.DISTANCE)) {
							int distance = pathObject.getInt(AmapConfigConstant.DISTANCE);
							directionResponse.setDistance(distance);
						}
						if (pathObject.has(AmapConfigConstant.DURATION)) {
							int duration = pathObject.getInt(AmapConfigConstant.DURATION);
							directionResponse.setDuration(duration);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return directionResponse;
	}
}
